import { useState, useEffect } from "react";
import { connect } from 'react-redux';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import Cookies from "js-cookie";
import { formatTimeString, formatActicityType } from '@/utils';
import { formatCouponData } from '../format_js';
// css
import styles from '@/styles/CommonOrder.module.scss';
// api
import { haveCoupons, haveCouponsList } from '@/api/coupon';
import { setProductInfo } from '@/store/actions/order';

const Coupon = ({ 
        data: { target, goodsId, goodsExtendId, goodsExtendName }, 
        order: { date, amount, startDate, endDate, salePrice, reducePrice },
        _setProductInfo
    }) => {

    const isHotel = target === '/hotel';
    const [collapse, setCollapse] = useState(false);
    const [haveCoupon, setHaveCoupon] = useState(false);
    const [coupons, setCoupons] = useState([]);
    const [uCoupons, setUCoupons] = useState([]);
    
    // 查询是否存在可用优惠券/查询优惠券
    useEffect(() => {
        const _haveCouponData = {
            distributorMobile: "",
            amount: amount || 1,
            status: 1,
            goodsExtendId,
            useTime: date,
            leaveDate: date
        }
        const _couponListdata = {
            distributorMobile: "",
            amount: amount || 1,
            goodsExtendId,
            comeDate: date,
            leaveDate: date,
            useTime: date,
        };
        Cookies.remove('order_coupon');
    
        // 酒店
        if(isHotel){
            _haveCouponData.useTime = startDate;
            _haveCouponData.leaveDate = endDate;

            _couponListdata.useTime = startDate;
            _couponListdata.comeDate = startDate;
            _couponListdata.leaveDate = endDate;
        }

        const _couponListdata1 = Object.assign({}, _couponListdata, {status: 1}),
            _couponListdata2 = Object.assign({}, _couponListdata, {status: 2});
        // 是否存在可用优惠券
        haveCoupons(_haveCouponData).then(res => {
            res.code === 0 && setHaveCoupon(res.data);
        });
        // 可用优惠券
        haveCouponsList(_couponListdata1).then(res => {
            const {code, data: { userCanUseCouponDTOList, activityRuleDetailsDTOList }} = res;
            code === 0 && setCoupons([
                ...userCanUseCouponDTOList.map(item => formatCouponData(item)),
                ...activityRuleDetailsDTOList.map(item => formatCouponData(item))
            ])
        });
        // 不可用
        haveCouponsList(_couponListdata2).then(res => {
            const {code, data: { userCanUseCouponDTOList, activityRuleDetailsDTOList }} = res;
            code === 0 && setUCoupons([
                ...userCanUseCouponDTOList.map(item => formatCouponData(item)),
                ...activityRuleDetailsDTOList.map(item => formatCouponData(item))
            ])
        });
    }, [date,amount,startDate,endDate]);

    // 选择优惠券
    function useCoupon (item){
        coupons.forEach(c => {
            if((item.couponId && item.couponId == c.couponId) || (item.activityBaseId && item.activityBaseId == c.activityBaseId)){
                c.chosen = !c.chosen;
                useCouponByPrice(c.chosen, item)
            }else{
                c.chosen = false;
            }
        });
        setCoupons([...coupons]);
    }
    // 使用优惠券，获取最新价格
    function useCouponByPrice (chosen, coupon){
        let _data = {
            goodsId,
            goodsExtendName,
            amount: Cookies.get('order_number'),
            startDate: date,
            endDate: date,
        }
        // 选中优惠券
        if(chosen){
            let { activityBaseId, activityRuleId, algorithms, couponId, saleType, saleRole, minusRule, reservationRole } = coupon;
            if(saleRole){
                saleType = saleRole.saleType;
            }else if(minusRule){
                saleType = minusRule.minusRuleAlgorithmList[0].saleType;
            }else if(reservationRole){
                saleType = reservationRole[0].saleType;
            }
            _data = {
                ..._data,
                couponId,
                activityBaseId,
                activityRuleId,
                saleType,
                algorithms,
            };
            Cookies.set('order_coupon', JSON.stringify(coupon));
        }else{
        // 不使用优惠券
            Cookies.remove('order_coupon');
        }
        // 若是酒店，时间节点为范围
        if(isHotel){
            _data.startDate = startDate;
            _data.endDate = endDate;
        }
        // 不是酒店
        if(!isHotel && Cookies.get('order_spIds')){
            _data.specificationsValueIds = Cookies.get('order_spIds');
        }

        _setProductInfo(_data);
    }

    if(!haveCoupon){
        return <></>
    }

    const couponPrice = (item) => {
        const { couponType } = item;
        return (
            <>
                <p className={styles['price']}>￥<em>{item.discountPrice || item.rebatePrice}</em></p>
                { couponType == 3 ? <p>无使用门槛</p> : ''}
                { couponType == 2 ? <p>满{item.satisfyPrice}可用</p> : ''}
                { couponType == 1 ? <p>体验券</p> : ''}
                { (couponType != 1 && couponType != 2 && couponType != 3) ? <p>{formatActicityType(item.algorithms)}</p> : ''}
            </>
        )
    }
    const couponInfo = (item) => {
        const { validityType } = item;
        return (
            <>
                <p className={styles['name']}>{item.name}</p>
                <p className={styles['time']}>
                    <span>有效期：</span>
                    {
                        validityType == 1
                        ? `${formatTimeString(item.startTime)}至${formatTimeString(item.endTime)}`
                        : `领取${item.validityDay || 0}天内有效`
                    }
                </p>
                <p className={styles['desc']}><span>使用规则：</span>{item.remark || '--'}</p>
            </>
        )
    }
    return (
        <div className={[styles['coupon-box'], collapse ? styles['collapse'] : ''].join(' ')}>
            <h3 className={styles['title']}>优惠/活动券
                <span>说明：1）优惠活动与优惠券不可同时使用；2）只能使用一张优惠券</span>
                <span onClick={() => { setCollapse(!collapse) }}>
                    { collapse ? <DownOutlined title="展开" /> : <UpOutlined title="收起" /> }
                </span>
            </h3>
            <div className={styles['coupon-list']}>
                {
                    coupons.map(item => {
                        return (
                            <div className={[styles['item'], item.chosen && styles['chosen']].join(' ')}
                                 key={item.couponId || item.activityBaseId}
                                 onClick={() => { useCoupon(item) }}
                            >
                                <div className={styles['left']}>{couponPrice(item)}</div>
                                <div className={styles['center']}>{couponInfo(item)}</div>
                                <div className={styles['right']}><span></span></div>
                            </div>
                        )
                    })
                }
                {
                    uCoupons.map((item, index) => {
                        return (
                            <div className={[styles['item'], styles['disabled']].join(' ')} key={index}>
                                <div className={styles['left']}>{couponPrice(item)}</div>
                                <div className={styles['center']}>{couponInfo(item)}</div>
                            </div>
                        )
                    })
                }
                {
                    coupons.length && reducePrice
                    ? <p className={styles['price-total-box']}>
                        <span>费用合计：<em>￥</em><strong>{salePrice}</strong></span>
                        <span>优惠金额：<em>￥</em><strong>{reducePrice}</strong></span>
                      </p>
                    : ""
                }
            </div>
        </div>
    )
};

const mapStateToProps = (state) => {
    return {
        order: state.order
    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        _setProductInfo: (v) => dispatch(setProductInfo(v))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Coupon)